#include "logindialog.h"
#include "ui_logindialog.h"
#include <QDebug>
#include <QtCore>

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::accept()
{
    QString content = ui->packageLineEdit->text();
    this->package = content;
    if(!content.isEmpty()){
        QString dirStr = qApp->applicationDirPath()+"/data/"+content;
        QDir dir;
        if(!dir.exists(dirStr))//判断需要创建的文件夹是否存在
        {
            dir.mkdir(dirStr); //创建文件夹
        }
        QString dbName = dirStr+"/"+content+".db";
        if(copyFileToPath(":/file/student.db",dbName,false)){
            qDebug()<<dbName+" copy YES!"<<endl;
        }else{
            qDebug()<<dbName+" copy NO!"<<endl;
        }
        QFile file1;
        file1.setFileName(dbName);
        file1.setPermissions(QFlag(0x4000|0x2000|0x0400|0x0200|0x0040|0x0020));

        emit packageChanged(content);
        QDialog::accept();
    }else{
        QDialog::rejected();
    }
}

bool LoginDialog::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)
{
    toDir.replace("\\","/");
    if (sourceDir == toDir){
        return true;
    }
    if (!QFile::exists(sourceDir)){
        return false;
    }
    QDir *createfile     = new QDir;
    bool exist = createfile->exists(toDir);
    if (exist){
        if(coverFileIfExist){
            createfile->remove(toDir);
        }
    }//end if

    if(!QFile::copy(sourceDir, toDir))
    {
        return false;
    }
    return true;
}
